package wang.hex;

import net.sf.cglib.proxy.Enhancer;

import java.lang.reflect.Modifier;
import java.util.*;

/**
 * @Author fox
 * @Class TracerFactory
 * @Description
 * @Date 2020/12/24 11:42
 */
public class TracerFactory {

    public static final List<TracerMethodVisitor> visitors = new LinkedList<TracerMethodVisitor>();
    public static final Set<Class> noTraceClazz = new HashSet<Class>();


    /**
     * 添加环切
     *
     * @param v
     */
    public static void addVisitors(TracerMethodVisitor v) {
        visitors.add(v);
    }

    /**
     * 跳过该类的方法以及该类一下的方法
     *
     * @param clazz
     */
    public static void addNoTraceClass(Class clazz) {
        noTraceClazz.add(clazz);
    }

    public static <T> T getTracerFromObject(Object o) {
        if (o == null) {
            return null;
        }
        Class aClass = o.getClass();
        //如果已经是代理类 或者是final类 或者不需要代理则直接返回
        if (aClass.getSimpleName().contains("$$EnhancerByCGLIB$$") || Modifier.isFinal(aClass.getModifiers()) || noTraceClazz.contains(aClass)) {
            return (T) o;
        }
        Enhancer enhancer = new TracerEnhancer();
        enhancer.setSuperclass(aClass);
        enhancer.setCallback(new TracerInterceptor(o));
        return (T) enhancer.create();
    }
}

